package com.huluobo.a2307douyindemo.utils

import BaseCallBack
import android.Manifest
import android.app.Activity
import android.app.AlertDialog
import android.content.Context
import android.content.DialogInterface
import android.content.DialogInterface.OnClickListener
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Build
import android.provider.Settings
import androidx.core.app.ActivityCompat
import com.blankj.utilcode.util.SPUtils
import com.huluobo.lib_base.net.Const

/**
 *  Created by LC on 2025/9/26.
 *  权限工具类,可以保存给出的权限
 */
class PermissionUtils(private val activity: Activity, private val context: Context) {
    companion object {
        //请求权限的请求码
        const val PERMISSION_REQUEST_CODE = 10910

        //授权
        const val AUTHORIZED = 0

        //拒绝
        const val REJECTED = 1

        //未授权
        const val UNAUTHORIZED = 2

        //取消
        const val CANCEL = 3

        //永久拒绝
        const val ALWAYS_DENIED = -1

        //摄像头权限
        var camera = Manifest.permission.CAMERA

        //写入权限
        var write = Manifest.permission.WRITE_EXTERNAL_STORAGE

        //敏感权限
        //读取视频权限,需要判断当前sdk版本是否大于33,如果大于,声明读取视频权限,其他版本sdk声明读取sd卡权限
        var video =
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) Manifest.permission.READ_MEDIA_VIDEO
            else Manifest.permission.READ_EXTERNAL_STORAGE

        //读取图片的权限,与视频权限类似,需要判断版本
        var image = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) Manifest.permission.READ_MEDIA_IMAGES
        else Manifest.permission.READ_EXTERNAL_STORAGE

        //录音麦克风权限
        var microphone = Manifest.permission.RECORD_AUDIO

        //打电话权限
        var callPhone = Manifest.permission.CALL_PHONE

        //设备权限,读取设备转改
        var device = Manifest.permission.READ_PHONE_STATE

        //定位权限,需要有个2个Location权限
        var location = arrayOf(Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION)
    }

    //声明权限的返回 类型为授权非授权和取消这类的int
    private lateinit var calback: BaseCallBack<Int>

    //需要声明的权限数组
    private lateinit var permissionIds: Array<String>

    //设置返回回调
    fun setCallBack(callBack: BaseCallBack<Int>) {
        this.calback = callBack
    }

    //声明权限枚举
    enum class Type {
        CallPhone, Camera, Video, Image, Microphone, Device, Location, Write
    }

    fun requestPermission(type: Type): Int {
        permissionIds = when (type) {
            Type.CallPhone -> arrayOf(callPhone)
            Type.Camera -> arrayOf(camera)
            Type.Video -> arrayOf(video)
            Type.Image -> arrayOf(image)
            Type.Microphone -> arrayOf(microphone)
            Type.Device -> arrayOf(device)
            Type.Location -> location
            Type.Write -> arrayOf(write)
        }

        return when (checkPermission(permissionIds)) {
            UNAUTHORIZED -> {
                //给出权限类型,返回未授权
                getPermission(type)
                UNAUTHORIZED
            }

            AUTHORIZED -> {
                AUTHORIZED
            }

            else -> {
                val alertDialog = AlertDialog.Builder(context)
                    .setTitle("提示")
                    .setMessage("此权限已经被拒绝访问。您想进入设置进行修改吗？")
                    .setPositiveButton("确认") { _, _ ->
                        val packageName = "com.huluobo.a2307douyindemo"
                        //跳转到系统的设置页面
                        val intent = Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS)
                        intent.data = Uri.parse("package:$packageName")
                        context.startActivity(intent)
                    }
                    .setNegativeButton(
                        "取消"
                    ) { _, _ -> }.create()
                alertDialog.setCanceledOnTouchOutside(false)
                alertDialog.show()
                REJECTED
            }
        }
    }

    /**
     * 检查权限的方法
     */
    private fun checkPermission(permissionIds: Array<String>): Int {
        val status: MutableList<Int> = ArrayList()
        //遍历权限id集合
        for (permissionId in permissionIds) {
            val state: String? = SPUtils.getInstance().getString(Const.KEY_PERMISSION)
            if (state == null) {
                status.add(UNAUTHORIZED)
            } else if (Const.KEY_ALWAYS_DENIED == state) {
                if (ActivityCompat.checkSelfPermission(context, permissionId) == PackageManager.PERMISSION_GRANTED) {
                    SPUtils.getInstance().put(permissionId, Const.KEY_AUTHORIZED)
                    status.add(AUTHORIZED)
                } else {
                    status.add(REJECTED)
                }
            } else {
                if (ActivityCompat.checkSelfPermission(context, permissionId) == PackageManager.PERMISSION_GRANTED) {
                    status.add(AUTHORIZED)
                } else {
                    SPUtils.getInstance().put(permissionId, Const.KEY_ALWAYS_DENIED)
                    status.add(REJECTED)
                }
            }
        }

        if (status.contains(REJECTED)) return REJECTED
        return if (status.contains(UNAUTHORIZED)) UNAUTHORIZED else AUTHORIZED
    }

    private fun getPermission(type: Type) {
        var message = ""
        when (type) {
            Type.Camera -> message =
                "当您使用设备的相机二维码、拍照或拍摄视频时，您需要访问设备的相机相关权限。如果您拒绝提供，您将无法使用此功能"

            Type.Video -> message =
                "当您使用设备的上传功能时，您需要访问设备的读取视频相关权限。如果您拒绝提供，您将无法使用此功能"

            Type.Image -> message =
                "当您使用设备的上传功能时，您需要访问设备的读取图片相关权限。如果您拒绝提供，您将无法使用此功能"

            Type.Microphone -> message =
                "当您使用设备的录音功能时，您需要访问设备的读取麦克风相关权限。如果您拒绝提供，您将无法使用此功能"

            Type.Device -> message =
                "当您使用我们的视频播放和视频展示服务时，您需要手机您的一些信息，包括设备型号，设备唯一名称等。如果您拒绝提供，您将无法使用此功能"

            Type.Location -> message =
                "当您使用本地生活服务查看附近的合作商家时，您需要访问设备的权限。如果您拒绝提供，您将无法使用此功能"

            Type.Write -> message =
                "当您使用我们的图片/视频存储功能时，我们需要获取您设备存储的权限。如果您拒绝提供，您将无法使用此功能"

            else -> {}
        }

        val alertDialog = AlertDialog.Builder(context)
            .setTitle("提示")
            .setMessage(message)
            .setPositiveButton(
                "确认"
            ) { _, _ ->
                ActivityCompat.requestPermissions(
                    activity, permissionIds, PERMISSION_REQUEST_CODE
                )
            }.setNegativeButton(
                "取消"
            ) { _, _ ->
                calback.success(CANCEL)
            }.create()
        //点击外部不可消失
        alertDialog.setCanceledOnTouchOutside(false)
        alertDialog.show()
    }

    //当请求权限返回的时候的操作
    fun onRequestPermissionsResult(
        permissionIds: Array<String>, grantResults: IntArray
    ) {
        if (grantResults[0] == AUTHORIZED) {
            SPUtils.getInstance().put(permissionIds[0], Const.KEY_AUTHORIZED)
            calback.success(AUTHORIZED)
        }
        if (grantResults[0] == ALWAYS_DENIED) {
            SPUtils.getInstance().put(permissionIds[0], Const.KEY_ALWAYS_DENIED)
            calback.success(REJECTED)
        }
    }
}